package geo.com.geosdkdemo.bluetooth;

import android.Manifest;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.widget.Toast;

import java.lang.reflect.Method;
import java.util.ArrayList;

import geo.com.geosdkdemo.view.adapter.BlueToothDeviceAdapter;

import static android.app.Activity.RESULT_OK;

/*
 * author: caojunhao
 * date  : 2020/4/28
 * desc  :蓝牙初始化类
 */
public class BlueToothInit implements IBlueToothInit {
    private Activity mActivity;
    private Context mContext;
    private BluetoothAdapter mBtAdatper;
    private BlueToothDeviceAdapter mAdapter;
    private volatile static BlueToothInit singleton; //volatile 能够防止代码的重排序，保证得到的对象是初始化过
    public static final int PERMISSIONS_REQUEST_CODE_ACCESS_COARSE_LOCATION=1;
    public static final int PERMISSIONS_REQUEST_CODE_WRITE_EXTERNAL_STORAGE=2;


    public BlueToothInit(Context context, BluetoothAdapter btAdatper, BlueToothDeviceAdapter adapter){
        mAdapter=adapter;
        mActivity= (Activity) context;
        mContext=context;
        mBtAdatper = btAdatper;
    }

    //打开蓝牙
    @Override
    public void openBlueTooth() {
        //1.判断当前设备是否支持蓝牙设备
        if (mBtAdatper == null) {//不支持蓝牙设备
            Toast.makeText(mContext, "当前设备不支持蓝牙功能", Toast.LENGTH_SHORT).show();
            return;
        }
        //2.判断当前蓝牙设备是否可用
        if (!mBtAdatper.isEnabled()) {//设备不可用时打开蓝牙设备
            //弹窗询问方式打开蓝牙
            Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);//蓝牙适配器. 行动-请求-打开
            mActivity.startActivityForResult(intent,RESULT_OK);
        }
    }

    //关闭蓝牙
    @Override
    public void closeBlueTooth(){
        if(mBtAdatper.isEnabled()){
            mBtAdatper.disable();
        }
    }

    //判断蓝牙是否打开
    @Override
    public boolean isOpenBlueTooth(){
        if(mBtAdatper!=null){
            return mBtAdatper.isEnabled();
        }
        return false;
    }

    //搜索蓝牙
    @Override
    public void searchBlueTooth() {
        // 判断蓝牙是否已打开
        if(mBtAdatper==null)
            return;
        if (!mBtAdatper.isEnabled()) {
            Toast.makeText(mContext, "请先打开蓝牙", Toast.LENGTH_SHORT).show();
        }
        //判断蓝牙是否正在扫描，如果是调用取消扫描方法；如果不是，则开始扫描
        if (mBtAdatper.isDiscovering()) {
            mBtAdatper.cancelDiscovery();
        }
         mBtAdatper.startDiscovery();
    }

    //搜索蓝牙前请求定位权限（6.0以上显示蓝牙列表需开启定位权限）
    @Override
    public boolean requestPermission(){
        mAdapter.clear();
        return checkPermission();
    }

    /**
     * 检测是否拥有相关权限;
     */
    private boolean checkPermission() {
        ArrayList<String > mListPermission=new ArrayList<>();
        if (ContextCompat.checkSelfPermission(mContext,
                Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            // 检查读写权限;
            mListPermission.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        }

        if (ContextCompat.checkSelfPermission(mContext,
                Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // 检查获取 定位信息 ;
            mListPermission.add(Manifest.permission.ACCESS_FINE_LOCATION);
        }

        if(mListPermission.size()>0) {
            String[] strs=new String[mListPermission.size()];
            ActivityCompat.requestPermissions(mActivity, mListPermission.toArray(strs), PERMISSIONS_REQUEST_CODE_ACCESS_COARSE_LOCATION);
            return false;
        }

        return true;
    }


    //返回匹配状态--true:成功匹配
    @Override
    public boolean getBondState(BluetoothDevice device){
        int bondState = device.getBondState();
        //未配对
        if (BluetoothDevice.BOND_NONE == bondState){
            //没有进行匹配先进行匹配
            try{
                //蓝牙匹配的方法
                Method createBond = BluetoothDevice.class.getMethod("createBond");
                createBond.invoke(device);
            }catch(Exception e) {
                e.printStackTrace();
                Toast.makeText(mContext,"无法执行配对", Toast.LENGTH_SHORT).show();
            }
            //匹配成功
        }else if(BluetoothDevice.BOND_BONDED == bondState){
            return true;
        }
        return false;
    }

    //停止搜索蓝牙
    @Override
    public void stopSearchBlueTooth() {
        //判断蓝牙是否正在扫描，如果是调用取消扫描方法；如果不是，则开始扫描
        if (mBtAdatper.isDiscovering()) {
            mBtAdatper.cancelDiscovery();
        }
    }
}
